<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 电影场次数据
const sessions = ref([])

// 总记录数
const total = ref(0)

// 分页参数
const pagination = ref({
  pageSize: 10,
  pageNum: 1
})

// 搜索条件
const searchForm = ref({
  movieName: '',
  hallType: '',
  startTime: ''
})

// 影厅类型选项
const hallTypes = ref([
  { label: '全部', value: '' }
])

// 影厅列表
const venues = ref([])

// 电影列表
const movies = ref([])

// 弹窗控制
const dialogVisible = ref({
  addHall: false,
  addSession: false
})

// 添加影厅表单
const addHallForm = ref({
  name: '',
  typeId: '',
  x: 1,
  y: 1
})

// 添加电影场次表单
const addSessionForm = ref({
  venueId: '',
  movieId: '',
  money: 0,
  startTime: ''
})

// 获取影厅类型数据
const getHallTypes = async () => {
  try {
    const response = await axios.get('http://db.etoak.com:9527/seat/selectVenueType')
    if (response.data.flag) {
      // 添加影厅类型到选项中
      response.data.data.forEach(type => {
        hallTypes.value.push({
          label: type.name,
          value: type.id.toString()
        })
      })
    } else {
      console.error('获取影厅类型失败:', response.data.msg)
    }
  } catch (error) {
    console.error('请求影厅类型接口失败:', error)
  }
}

// 获取影厅列表
const getVenues = async () => {
  try {
    const response = await axios.get('http://db.etoak.com:9527/seat/selectAllVenue')
    if (response.data.flag) {
      venues.value = response.data.data
    } else {
      console.error('获取影厅列表失败:', response.data.msg)
    }
  } catch (error) {
    console.error('请求影厅列表接口失败:', error)
  }
}

// 获取电影列表
const getMovies = async () => {
  try {
    const response = await axios.get('http://db.etoak.com:9527/seat/selectAllMovie')
    if (response.data.flag) {
      movies.value = response.data.data
    } else {
      console.error('获取电影列表失败:', response.data.msg)
    }
  } catch (error) {
    console.error('请求电影列表接口失败:', error)
  }
}

// 获取电影场次数据
const getSessions = async () => {
  try {
    const params = {
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.pageNum,
      movieName: searchForm.value.movieName,
      typeId: searchForm.value.hallType || undefined,
      startTime: searchForm.value.startTime || undefined
    }

    const response = await axios.post('http://db.etoak.com:9527/seat/pageMovie', params)
    if (response.data.flag) {
      total.value = response.data.data.total
      sessions.value = response.data.data.scenesList.map(session => ({
        id: session.id,
        hall: session.venueName,
        movie: session.movieName,
        type: session.typeName,
        time: session.startTime,
        price: session.money,
        duration: session.longTime,
        capacity: session.x * session.y,
        ticketsLeft: (session.x * session.y) - (session.sale || 0)
      }))
    } else {
      console.error('获取电影场次失败:', response.data.msg)
    }
  } catch (error) {
    console.error('请求电影场次接口失败:', error)
  }
}

// 搜索方法
const searchSessions = () => {
  pagination.value.pageNum = 1
  getSessions()
}

// 清空搜索条件
const clearSearch = () => {
  searchForm.value = {
    movieName: '',
    hallType: '',
    startTime: ''
  }
  pagination.value.pageNum = 1
  getSessions()
}

// 删除场次
const deleteSession = async (id) => {
  try {
    const response = await axios.delete(`http://db.etoak.com:9527/seat/delMovie/${id}`)
    if (response.data.flag) {
      // 删除成功，刷新列表
      getSessions()
      ElMessage({ message: '删除电影场次成功', type: 'success' })
    } else {
      ElMessage({ message: `删除失败: ${response.data.msg}`, type: 'error' })
    }
  } catch (error) {
    console.error('删除电影场次接口失败:', error)
    ElMessage({ message: '删除失败，请重试', type: 'error' })
  }
}

// 添加影厅
const addHall = async () => {
  try {
    const response = await axios.post('http://db.etoak.com:9527/seat/addMovieVenue', addHallForm.value)
    if (response.data.flag) {
      ElMessage.success(response.data.msg)
      dialogVisible.value.addHall = false
      // 重置表单
      addHallForm.value = {
        name: '',
        typeId: '',
        x: 1,
        y: 1
      }
      getVenues() // 重新获取影厅数据
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    console.error('添加影厅失败', error)
    ElMessage.error('添加影厅失败，请重试')
  }
}
    
  // 添加电影场次
  const addMovieSession = async () => {
    try {
      // 格式化时间为yyyy-MM-dd HH:mm:ss格式
      const formattedStartTime = addSessionForm.value.startTime ? new Date(addSessionForm.value.startTime).toISOString().slice(0, 19).replace('T', ' ') : ''
      const sessionData = {
        ...addSessionForm.value,
        startTime: formattedStartTime
      }
      const response = await axios.post('http://db.etoak.com:9527/seat/addScenes', sessionData)
      if (response.data.flag) {
        ElMessage.success(response.data.msg)
        dialogVisible.value.addSession = false
        // 重置表单
        addSessionForm.value = {
          venueId: '',
          movieId: '',
          money: 0,
          startTime: ''
        }
        getSessions() // 重新获取场次数据
      } else {
        ElMessage.error(response.data.msg)
      }
    } catch (error) {
      console.error('添加电影场次失败', error)
      ElMessage.error('添加电影场次失败，请重试')
    }
  }


// 分页变更
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  getSessions()
}

const handleCurrentChange = (current) => {
  pagination.value.pageNum = current
  getSessions()
}

// 初始加载数据
onMounted(async () => {
  await getHallTypes()
  await getVenues()
  await getMovies()
  await getSessions()
})
</script>

<template>
  <div class="movie-management-page">
    <!-- 顶部导航栏 -->

    <!-- 顶部导航栏 -->
    <el-header style="background-color: #2c3e50; color: white;">
      <div class="tille" style="display: flex; justify-content: space-between; align-items: center; height: 100%;">
        <img src="logo.png" alt="Logo" style="height: 30px;" />
        <div style="display: flex; gap: 20px;">
          <router-link to="/home" custom v-slot="{ navigate, isActive }">
            <span
              @click="navigate"
              role="link"
              :class="{'active': isActive}"
              style="color: white; cursor: pointer;"
            >
              购票首页
            </span>
          </router-link>
          <router-link to="/movie-sessions-management" custom v-slot="{ navigate, isActive }">
            <span
              @click="navigate"
              role="link"
              :class="{'active': isActive}"
              style="color: white; cursor: pointer;"
            >
              电影场次管理
            </span>
          </router-link>
        </div>
        <span style="color: white;">欢迎您回来 hhh</span>
      </div>
    </el-header>

    <div id="center" style="width: 90%; margin: 20px auto;">

      <el-form :inline="true" :model="searchForm" class="demo-form-inline" style="margin-bottom: 20px;">
        <el-form-item label="电影名称" style="width: 200px">
          <el-input v-model="searchForm.movieName" placeholder="模糊查询" clearable />
        </el-form-item>
        <el-form-item label="影厅类型" style="width: 200px">
          <el-select v-model="searchForm.hallType" placeholder="请选择" clearable>
            <el-option v-for="type in hallTypes" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="开场时间">
          <el-date-picker v-model="searchForm.startTime" type="date" placeholder="选择开始时间" format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSessions">查询</el-button>
          <el-button type="primary" @click="clearSearch">重置</el-button>
          <el-button type="primary" @click="dialogVisible.addHall = true">添加影厅</el-button>
          <el-button type="primary" @click="dialogVisible.addSession = true">添加电影场次</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="sessions" border style="width: 100%;">
        <el-table-column prop="hall" label="影厅" width="120" align="center"></el-table-column>
        <el-table-column prop="movie" label="电影名称" width="150" align="center"></el-table-column>
        <el-table-column prop="type" label="影厅类型" width="120" align="center"></el-table-column>
        <el-table-column prop="time" label="开场时间" width="180" align="center"></el-table-column>
        <el-table-column prop="price" label="票价" width="80" align="center">
          <template #default="scope">
            <span>{{ scope.row.price }}元</span>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="电影时长(分钟)" width="140" align="center"></el-table-column>
        <el-table-column prop="capacity" label="可容纳总人数" width="120" align="center"></el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button type="text" style="color: #F56C6C" @click="deleteSession(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="text-align: right; margin-top: 10px;">
        <el-pagination
          small
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pagination.pageSize"
          :current-page="pagination.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>
  </div>

  
  <!-- 添加影厅弹窗 -->
  <el-dialog v-model="dialogVisible.addHall" title="添加影厅" width="500px">
    <el-form :model="addHallForm" label-width="100px" style="margin-top: 20px;">
      <el-form-item label="影厅名称" prop="name">
        <el-input v-model="addHallForm.name" placeholder="请输入影厅名称" />
      </el-form-item>
      <el-form-item label="影厅类型" prop="typeId">
        <el-select v-model="addHallForm.typeId" placeholder="请选择影厅类型">
          <el-option v-for="type in hallTypes.filter(t => t.value)" :key="type.value" :label="type.label" :value="type.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="座位排数" prop="x">
        <el-input v-model.number="addHallForm.x" placeholder="请输入座位排数" type="number" min="1" />
      </el-form-item>
      <el-form-item label="座位列数" prop="y">
        <el-input v-model.number="addHallForm.y" placeholder="请输入座位列数" type="number" min="1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible.addHall = false">取消</el-button>
      <el-button type="primary" @click="addHall">确认</el-button>
    </template>
  </el-dialog>

  <!-- 添加电影场次弹窗 -->
  <el-dialog v-model="dialogVisible.addSession" title="添加电影场次" width="500px">
    <el-form :model="addSessionForm" label-width="100px" style="margin-top: 20px;">
      <el-form-item label="影厅选择" prop="venueId">
        <el-select v-model="addSessionForm.venueId" placeholder="请选择影厅">
          <el-option v-for="venue in venues" :key="venue.id" :label="venue.name" :value="venue.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="电影选择" prop="movieId">
        <el-select v-model="addSessionForm.movieId" placeholder="请选择电影">
          <el-option v-for="movie in movies" :key="movie.id" :label="movie.name" :value="movie.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="电影票价" prop="money">
        <el-input v-model.number="addSessionForm.money" placeholder="请输入电影票价" type="number" min="0" step="0.1" />
      </el-form-item>
      <el-form-item label="开场时间" prop="startTime">
        <el-date-picker v-model="addSessionForm.startTime" type="datetime" placeholder="选择开场时间" format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible.addSession = false">取消</el-button>
      <el-button type="primary" @click="addMovieSession">确认</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 这里可以添加相关的样式 */
.movie-management-page {
  font-family: Arial, sans-serif;
}

.tille {
  display: flex;
  justify-content: center;
}

#center {
  width: 90%;
  margin: 20px auto;
}

.el-table .cell {
  white-space: nowrap;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}
</style>